package com.example.zbh.dsliao;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

import com.easemob.chat.EMChat;
import com.easemob.chat.EMChatManager;
import com.easemob.util.EMLog;
import com.example.zbh.dsliao.application.App;
import com.example.zbh.dsliao.db.entity.DaoMaster;
import com.example.zbh.dsliao.db.entity.DaoSession;
import com.example.zbh.dsliao.ui.activty.VoiceCallActivity;

/**
 * Created by zbh on 15/11/26.
 */
public class DlHelper {
    private static DlHelper dlHelper;
    private static DaoMaster daoMaster;
    private static DaoSession daoSession;

    private CallReceiver callReceiver;
    private DlHelper(){

    }
    public static DlHelper getDlHelper(){
        if (dlHelper == null){
            dlHelper = new DlHelper();
        }
        return  dlHelper;
    }
    public static DaoMaster getDaoMaster(){
        if (daoMaster == null){
            DaoMaster.OpenHelper openHelper = new DaoMaster.DevOpenHelper(App.getContext(), "diaoyaolin", null);
            daoMaster = new DaoMaster(openHelper.getWritableDatabase());
        }
        return daoMaster;
    }
    public static DaoSession getDaoSession(){
        if (daoSession == null){
            if (daoMaster == null)
                getDaoMaster();
            daoSession = daoMaster.newSession();
        }
        return daoSession;
    }
    public void init(Context context){
        if (!isLoggedIn())
            return;
        IntentFilter intentFilter = new IntentFilter(EMChatManager.getInstance().getIncomingCallBroadcastAction());
        if (callReceiver == null){
            callReceiver = new CallReceiver();
        }
        context.registerReceiver(callReceiver, intentFilter);

    }
    public boolean isLoggedIn(){
        return EMChat.getInstance().isLoggedIn();
    }

    public class CallReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if(!isLoggedIn())
                return;
            //拨打方username
            String from = intent.getStringExtra("from");
            //call type
            String type = intent.getStringExtra("type");
            if("video".equals(type)){ //视频通话
//                context.startActivity(new Intent(context, VideoCallActivity.class).
//                        putExtra("username", from).putExtra("isComingCall", true).
//                        addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
            }else{ //音频通话
                context.startActivity(new Intent(context, VoiceCallActivity.class).
                        putExtra("username", from).putExtra("isComingCall", true).
                        addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
            }
            EMLog.d("CallReceiver", "app received a incoming call");
        }

    }




}
